package com.studyweb.controller;

import com.studyweb.pojo.vo.Result;
import com.studyweb.pojo.entity.QuantitativeQuestion;
import com.studyweb.service.QuantitativeQuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 数量模块控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/quantitative")
public class QuantitativeController {
    
    @Autowired
    private QuantitativeQuestionService quantitativeQuestionService;
    
    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result test() {
        return Result.success("QuantitativeController is working!");
    }
    
    /**
     * 获取数量题目列表
     */
    @GetMapping("/questions")
    public Result getQuestions(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subCategory,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) String orderType,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = quantitativeQuestionService.getQuestions(pageNum, pageSize, questionType, difficulty, category, subCategory, keyword, orderBy, orderType);
            return Result.success("获取数量题目列表成功", result);
        } catch (Exception e) {
            log.error("获取数量题目列表异常：{}", e.getMessage(), e);
            return Result.error("获取数量题目列表失败");
        }
    }
    
    /**
     * 创建数量题目
     */
    @PostMapping("/questions")
    public Result createQuestion(@Valid @RequestBody QuantitativeQuestion question, HttpServletRequest request) {
        try {
            // 从request中获取当前用户ID（由拦截器设置）
            Long userId = (Long) request.getAttribute("userId");
            if (userId == null) {
                return Result.error("用户未登录");
            }
            
            // 设置用户ID到题目对象中
            question.setUserId(userId);
            
            QuantitativeQuestion createdQuestion = quantitativeQuestionService.createQuestion(question);
            if (createdQuestion != null) {
                // 返回创建的题目对象，包含ID
                return Result.success("创建数量题目成功", createdQuestion);
            } else {
                return Result.error("创建数量题目失败");
            }
        } catch (Exception e) {
            log.error("创建数量题目异常：{}", e.getMessage(), e);
            return Result.error("创建数量题目失败");
        }
    }
    
    /**
     * 获取数量题目详情
     */
    @GetMapping("/questions/{id}")
    public Result getQuestion(@PathVariable Long id) {
        try {
            QuantitativeQuestion question = quantitativeQuestionService.getQuestionById(id);
            if (question != null) {
                return Result.success("获取数量题目详情成功", question);
            } else {
                return Result.error("数量题目不存在");
            }
        } catch (Exception e) {
            log.error("获取数量题目详情异常：{}", e.getMessage(), e);
            return Result.error("获取数量题目详情失败");
        }
    }
    
    /**
     * 更新数量题目
     */
    @PutMapping("/questions/{id}")
    public Result updateQuestion(@PathVariable Long id, @Valid @RequestBody QuantitativeQuestion question) {
        try {
            question.setQuestionId(id);
            boolean success = quantitativeQuestionService.updateQuestion(question);
            if (success) {
                return Result.success("更新数量题目成功");
            } else {
                return Result.error("更新数量题目失败");
            }
        } catch (Exception e) {
            log.error("更新数量题目异常：{}", e.getMessage(), e);
            return Result.error("更新数量题目失败");
        }
    }
    
    /**
     * 删除数量题目
     */
    @DeleteMapping("/questions/{id}")
    public Result deleteQuestion(@PathVariable Long id) {
        try {
            boolean success = quantitativeQuestionService.deleteQuestion(id);
            if (success) {
                return Result.success("删除数量题目成功");
            } else {
                return Result.error("删除数量题目失败");
            }
        } catch (Exception e) {
            log.error("删除资料分析题目异常：{}", e.getMessage(), e);
            return Result.error("删除资料分析题目失败");
        }
    }
    
    /**
     * 更新资料分析题目解析和正确答案
     */
    @PutMapping("/questions/{id}/explanation")
    public Result updateQuestionExplanation(@PathVariable Long id, @RequestBody Map<String, String> explanationData) {
        try {
            QuantitativeQuestion question = quantitativeQuestionService.getQuestionById(id);
            if (question == null) {
                return Result.error("数量题目不存在");
            }
            
            String explanation = explanationData.get("explanation");
            if (explanation == null || explanation.isEmpty()) {
                return Result.error("解析内容不能为空");
            }
            
            question.setExplanation(explanation);
            
            // 如果提供了正确答案，也更新正确答案
            String correctAnswer = explanationData.get("correctAnswer");
            if (correctAnswer != null && !correctAnswer.isEmpty()) {
                question.setCorrectAnswer(correctAnswer);
            }
            
            boolean success = quantitativeQuestionService.updateQuestion(question);
            if (success) {
                return Result.success("更新数量题目解析和正确答案成功");
            } else {
                return Result.error("更新数量题目解析和正确答案失败");
            }
        } catch (Exception e) {
            log.error("更新资料分析题目解析和正确答案异常：{}", e.getMessage(), e);
            return Result.error("更新数量题目解析和正确答案失败");
        }
    }

    /**
     * 批量删除题目
     */
    @DeleteMapping("/questions/batch")
    public Result batchDeleteQuestions(@RequestBody List<Long> ids) {
        try {
            boolean success = quantitativeQuestionService.batchDeleteQuestions(ids);
            if (success) {
                return Result.success("批量删除数量题目成功");
            } else {
                return Result.error("批量删除数量题目失败");
            }
        } catch (Exception e) {
            log.error("批量删除资料分析题目异常：{}", e.getMessage(), e);
            return Result.error("批量删除数量题目失败");
        }
    }
    
    /**
     * 获取练习题目
     */
    @GetMapping("/practice")
    public Result getPracticeQuestions(
            @RequestParam(defaultValue = "10") int count,
            @RequestParam(required = false) String difficulty,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String subCategory,
            @RequestParam(required = false) String questionType,
            @RequestParam(required = false) String orderBy,
            @RequestParam(required = false) String orderType,
            HttpServletRequest request) {
        try {
            log.info("获取练习题目参数: count={}, difficulty={}, category={}, subCategory={}, questionType={}, orderBy={}, orderType={}", count, difficulty, category, subCategory, questionType, orderBy, orderType);
            List<QuantitativeQuestion> questions = quantitativeQuestionService.getPracticeQuestions(count, difficulty, category, subCategory, questionType, orderBy, orderType);
            return Result.success("获取练习题目成功", questions);
        } catch (Exception e) {
            log.error("获取练习题目异常：{}", e.getMessage(), e);
            return Result.error("获取练习题目失败");
        }
    }
    
    /**
     * 提交答案
     */
    @PostMapping("/submit")
    public Result submitAnswer(@RequestBody Map<String, Object> answerData, HttpServletRequest request) {
        try {
            Map<String, Object> result = quantitativeQuestionService.submitAnswer(answerData);
            return Result.success("提交答案成功", result);
        } catch (Exception e) {
            log.error("提交答案异常：{}", e.getMessage(), e);
            return Result.error("提交答案失败");
        }
    }
    
    /**
     * 获取答题结果
     */
    @GetMapping("/results")
    public Result getResults(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Map<String, Object> result = quantitativeQuestionService.getResults(pageNum, pageSize);
            return Result.success("获取答题结果成功", result);
        } catch (Exception e) {
            log.error("获取答题结果异常：{}", e.getMessage(), e);
            return Result.error("获取答题结果失败");
        }
    }
}